//
//  BrowseViewController.m
//  CarHome
//
//  Created by 张世琦 on 14-9-27.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "BrowseViewController.h"
#import "DepreTableViewCell.h"
#import "Db.h"
#import "DepreModel.h"
#import "HistoryViewController.h"

NSString *const browseCell = @"cellId";

@interface BrowseViewController ()

@end

@implementation BrowseViewController

- (void)dealloc
{
    [_tableArray release];
    [_dbArray release];
    _dbArray = nil;
    _tableArray = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _tableArray = [[NSMutableArray alloc] init];
        self.dbArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    [self seleteAll];
    [self createBack];
    [self createTableView];
    if ([_dbArray count] == 0) {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您还没有浏览过汽车信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        [view release];
        
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}

#pragma mark -
#pragma mark 创建button

- (void)createBack
{
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 64)];
    aView.backgroundColor = myColor_dark;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(10, 20, 40, 44)];
    [button setImage:[UIImage imageNamed:@"BackButton.png"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [aView addSubview:button];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, 100, 44)];
    label.text = @"浏览记录";
    label.textAlignment = NSTextAlignmentCenter;
    [label setTextColor:[UIColor whiteColor]];
    [aView addSubview:label];
    UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
    [delete setFrame:CGRectMake(230, 20, 90, 44)];
    [delete setTitle:@"清空" forState:UIControlStateNormal];
    [delete setImage:[UIImage imageNamed:@"Depredate_DrawerButton.png"] forState:UIControlStateNormal];
    [delete setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [delete addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    [aView addSubview:delete];
    [self.view addSubview:aView];
    [aView release];
}

- (void)buttonAction:(id)sender
{
    [self dismissViewControllerAnimated:NO completion:nil];
}

#pragma mark -
#pragma mark 清除数据库

- (void)deleteAction:(id)sender
{
    
//    [self seleteAll];
   sqlite3 *db = [Db openDataBase];
    
    for (int i = 0; i < [_dbArray count]; i++) {
        NSString *sqlStr = [NSString stringWithFormat:@"delete from browse where car_id = %d", i];
        sqlite3_exec(db, [sqlStr UTF8String], nil, nil, nil);
    }
    [_dbArray removeAllObjects];
    [self.table reloadData];
}

#pragma mark -
#pragma mark 创建tableview

- (void)createTableView
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 320, self.view.frame.size.height - 64)];
    [_table registerClass:[DepreTableViewCell class] forCellReuseIdentifier:browseCell];
    _table.dataSource = self;
    _table.delegate = self;
    [self.view addSubview:_table];
    [_table release];
}

#pragma mark -
#pragma mark UITableView协议

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dbArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DepreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:browseCell forIndexPath:indexPath];
    DepreModel *model = [_dbArray objectAtIndex:indexPath.row];
    [cell setCarUrl:model.specpic name:model.seriesname type:model.specname depre:model.dealerprice price:model.fctprice city:model.car.city shop:model.car.shortname sell:model.car.orderrange typeUrl:model.styledinventorystate];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DepreModel *model = [_dbArray objectAtIndex:indexPath.row];
    HistoryViewController *history = [[HistoryViewController alloc] init];
    [history setWebUrl:[NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.2/content/dealer/downprice-a1-pm2-v4.2.0-sp%@-n%@-t%@-d%@-ss%@-nt%@.html",model.specid, model.articleid, model.articletype, model.car.carId, model.seriesid, model.car.ispromotion]];
    [self presentViewController:history animated:NO completion:nil];
    [history release];
}

#pragma mark -
#pragma mark 数据库查询

- (void)seleteAll
{
    sqlite3 *db = [Db openDataBase];
    [_dbArray removeAllObjects];
    //制作sqlite替身
    sqlite3_stmt *stmt = nil;
    //数据库语句
    NSString *sqlStr = [NSString stringWithFormat:@"select * from browse"];
    //根据数据库语句将从db中查询到内容赋值给替身(-1代表无限长)
    int result = sqlite3_prepare_v2(db, [sqlStr UTF8String], -1, &stmt, nil);
    //定义数组存储所有数据信息
    if (result == SQLITE_OK) {
        //根据stmt中内容逐条获取数据
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //把每条数据的每一个列取出来
            //            int carId = sqlite3_column_int(stmt, 0);
            const unsigned char *carImg = sqlite3_column_text(stmt, 1);
            const unsigned char *carName = sqlite3_column_text(stmt, 2);
            const unsigned char *carTypename = sqlite3_column_text(stmt, 3);
            float carDepre = sqlite3_column_double(stmt, 4);
            float carPrice = sqlite3_column_double(stmt, 5);
            const unsigned char *carCity = sqlite3_column_text(stmt, 6);
            const unsigned char *carShop = sqlite3_column_text(stmt, 7);
            const unsigned char *carSell = sqlite3_column_text(stmt, 8);
            const unsigned char *carType = sqlite3_column_text(stmt, 9);
            const unsigned char *carSpecid = sqlite3_column_text(stmt, 10);
            const unsigned char *carArticleid = sqlite3_column_text(stmt, 11);
            const unsigned char *carArticletype = sqlite3_column_text(stmt, 12);
            const unsigned char *carid = sqlite3_column_text(stmt, 13);
            const unsigned char *carSeriesid = sqlite3_column_text(stmt, 14);
            const unsigned char *carIspromotion = sqlite3_column_text(stmt, 15);
            //将const 转换为nsstring
            NSString *car_img = [NSString stringWithUTF8String:(const char *)carImg];
            NSString *car_name = [NSString stringWithUTF8String:(const char *)carName];
            NSString *car_typename = [NSString stringWithUTF8String:(const char *)carTypename];
            CGFloat car_depre = carDepre;
            CGFloat car_price = carPrice;
            NSString *car_city = [NSString stringWithUTF8String:(const char *)carCity];
            NSString *car_shop = [NSString stringWithUTF8String:(const char *)carShop];
            NSString *car_sell = [NSString stringWithUTF8String:(const char *)carSell];
            NSString *car_type = [NSString stringWithUTF8String:(const char *)carType];
            NSString *car_specid = [NSString stringWithUTF8String:(const char *)carSpecid];
            NSString *car_articleid = [NSString stringWithUTF8String:(const char *)carArticleid];
            NSString *car_articletype = [NSString stringWithUTF8String:(const char *)carArticletype];
            NSString *car_carid = [NSString stringWithUTF8String:(const char *)carid];
            NSString *car_seriesid = [NSString stringWithUTF8String:(const char *)carSeriesid];
            NSString *car_ispromotion = [NSString stringWithUTF8String:(const char *)carIspromotion];
            DepreModel *model = [DepreModel depreModelWithimg:car_img name:car_name typename:car_typename depre:car_depre price:car_price city:car_city shop:car_shop sell:car_sell type:car_type specid:car_specid articleid:car_articleid articletype:car_articletype carid:car_carid seriesid:car_seriesid ispromotion:car_ispromotion];
            [_dbArray addObject:model];
        }
    }
    //清除替身
    sqlite3_finalize(stmt);
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
